//
//  SpecialViewController.m
//  Share_Home_F
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "SpecialViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "BaseTableViewModel.h"
#import "SpecialCell.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "SpecialDetailsViewController.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface SpecialViewController ()
{
    NSInteger number;
}
@property (nonatomic, retain)NSMutableArray *modelArr;
@property (nonatomic, retain)UIScrollView *scorllView;
//@property (nonatomic, retain)NSMutableArray *indexArr;
@property (nonatomic, retain)UIPageControl *pageControl;
@property (nonatomic, retain)NSMutableArray *arr;
//@property (nonatomic, assign)NSInteger *index;
@end

@implementation SpecialViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"专题";
        number = 2;
        self.modelArr = [NSMutableArray array];
      //  self.indexArr = [NSMutableArray array];
        self.arr = [NSMutableArray array];
        
    }
    [self dataJSON];
    [self data];
    return self;
}

-(void)data {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *str = @"http://ihome.cmfmobile.com:8080/sp/custom/getNewSpecial.do?pn=1";
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *arr = responseObject;
        for (NSInteger i = 0; i < arr.count; i++) {
            NSMutableDictionary *dic = arr[i];
            BaseTableViewModel *tableModel = [[BaseTableViewModel alloc] init];
            [tableModel setValuesForKeysWithDictionary:dic];
            
            [self.arr addObject:tableModel];
            [tableModel release];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error");
    }];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
   
    self.scorllView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    self.scorllView.backgroundColor = [UIColor cyanColor];
    self.scorllView.contentSize = CGSizeMake(WIDTH * 14, 0);
    self.tableView.tableHeaderView = self.scorllView;
    
    [self.tableView addSubview:self.scorllView];
    [_scorllView release];
    
    for (NSInteger i = 0; i < self.arr.count; i++) {
        NSURL *url = [NSURL URLWithString:[self.arr[i] pic]];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * i, 0, WIDTH, 200)];
        [imageView sd_setImageWithURL:url];
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoTapped:)];
        [imageView addGestureRecognizer:singleTap];
        
        
        [self.scorllView addSubview:imageView];
    }
   
    self.scorllView.bounces = NO;
    self.scorllView.pagingEnabled = YES;
    self.scorllView.delegate = self;

    [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(change) userInfo:nil repeats:YES];
    
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(130, 180, 100, 20)];
    self.pageControl.numberOfPages = self.arr.count - 1;
    [self.tableView addSubview:self.pageControl];
    [_pageControl release];
    
    
   
    [self addFooter];
}
-(void)dataJSON {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSString *str1 = @"http://ihome.cmfmobile.com:8080/sp/custom/getNewSpecial.do?pn=";
    NSString *str2 = [NSString stringWithFormat:@"%@%ld",str1, number];
    [manager GET:str2 parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *arr = responseObject;
        for (NSInteger i = 0; i < arr.count; i++) {
            NSMutableDictionary *dic = arr[i];
            BaseTableViewModel *tableModel = [[BaseTableViewModel alloc] init];
            [tableModel setValuesForKeysWithDictionary:dic];
            
            [self.modelArr addObject:tableModel];
           
            [tableModel release];
        }
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error");
    }];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.modelArr count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *reuse = @"special";
    SpecialCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[SpecialCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:reuse] autorelease];
    }
    
    cell.myTitle.text = [self.modelArr[indexPath.row] title];
    NSURL *url = [NSURL URLWithString:[self.modelArr[indexPath.row] pic]];
    [cell.myImageView sd_setImageWithURL:url];
    cell.myShortSummary.text = [self.modelArr[indexPath.row] introduction];
    cell.Myupdate.text = [self.modelArr[indexPath.row]updateTime];
    cell.Mykeyword.text = [self.modelArr[indexPath.row]keyword];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SpecialDetailsViewController *specialDVC = [[SpecialDetailsViewController alloc] init];
    specialDVC.str = [self.modelArr[indexPath.row]id];
    specialDVC.titleStr = [self.modelArr[indexPath.row] title];
    specialDVC.intro = [self.modelArr[indexPath.row]introduction];
    specialDVC.key = [self.modelArr[indexPath.row]keyword];
    specialDVC.picStr = [self.modelArr[indexPath.row]pic];
   CATransition *transition = [CATransition animation];
    transition.duration = 1;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    transition.type = @"suckEffect";
    transition.subtype = kCATransitionFromTop;
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    
    [self.navigationController pushViewController:specialDVC animated:YES];
    [specialDVC release];
}
-(void)photoTapped:(NSInteger)index {
    SpecialDetailsViewController *specialDVC = [[SpecialDetailsViewController alloc] init];
    specialDVC.str = [self.arr[self.pageControl.currentPage] id];
    [self.navigationController pushViewController:specialDVC animated:YES];
    [specialDVC release];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 130;
}
#pragma mark 图片轮播
-(void)change {
    NSInteger dx = self.scorllView.contentOffset.x;
    NSInteger pageName = dx / WIDTH;
    if (pageName != self.arr.count - 2) {
        self.scorllView.contentOffset = CGPointMake(dx + WIDTH, 0);
    } else if (pageName == self.arr.count - 2) {
        self.scorllView.contentOffset = CGPointMake(0, 0);
    }
}

#pragma mark 滑动时pageControl在变化
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSInteger pageNum = self.scorllView.contentOffset.x / WIDTH;
    self.pageControl.currentPage = pageNum;
}





-(void)addHeader {
    [self.tableView addHeaderWithCallback:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            
            [self.tableView headerEndRefreshing];
        });
    }];
    [self.tableView headerBeginRefreshing];
}
-(void)addFooter {
    [self.tableView addFooterWithCallback:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            number++;
            [self dataJSON];
            [self.tableView reloadData];
            
            [self.tableView footerEndRefreshing];
        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
